import req from '@/request.js'
const auth = window.context.baseUrl || ''

export default {
  getAuthorizeMessage(){
    return req.get(`${auth}/authorize/v1/get`)
  },
  authentication(principal, cb, errorCb) {
    let Base64 = require('js-base64').Base64
    req
      .post(auth + `/auth/v1/login`, {
        username: principal.account,
        password: principal.password.encryptWithRsa(),
        verificationKey: principal.verificationKey,
        verificationCode: principal.verificationCode
      })
      .then(function(rep) {
        cb(rep.data)
      })
      .catch(function(error) {
        errorCb(error.message)
      })
  },
  basicSso(token, cb, errorCb) {
    let service = localStorage.getItem('service')
    let ssoUserId = localStorage.getItem('ssoUserId')
    req
      .get(auth + `/auth/v1/sso/auth?ticket=${token}&code=${token}&service=${service}&ssoUserId=${ssoUserId}`)
      .then(function(rep) {
        cb(rep.data)
      })
      .catch(function(error) {
        errorCb(error.message)
      })
  },
  refreshAndGetAuthenticationToken() {
    return new Promise((resolve, reject) => {
      req
        .get(`${auth}/refresh`)
        .then(function(rep) {
          resolve(rep.data)
        })
        .catch(function(error) {
          reject(error.message)
        })
    })
  },
  logout() {
    return req.get(`${auth}/auth/v1/signout`)
  }
}
